#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <sys/signal.h>
#include <sys/stat.h>
#include <time.h>
#include "client.h"
#include "cl.h"

static void siginthandler(int sig);


int
main(int argc, char * argv[])
{
	int end = 0;
	char * inpbuf;
	
	if ((inpbuf= malloc(MAXLINE+1)) == NULL)
	{
		fprintf(stderr, "Memory allocation error\n");
		return 1;
	}

	system("clear");
	printf("Welcome!\n\n");
	
	startDB();
	signal(SIGINT, siginthandler);
	while (!end && input(PROMPT, inpbuf))
		end = process_line(inpbuf);
	
	free(inpbuf);
	printf("Thanks for using HotelDB!\n\n");
	return 0;
}
int
startDB(int * rooms, int * guests)
{
	int fd;
	
	if((fd = open("rooms.db", O_RDONLY)) != -1)
	{
		close(fd);
		if((fd = open("guests.db", O_RDONLY)) != -1)
		{
			close(fd);
			return 1;
		}
		else
		{
			/*the guest file does not exist, the rooms file is inconsistent and 
			 * must be terminated before creating the new guests files */
			unlink("rooms.db");
			
			if((*rooms = open("rooms.db", O_WRONLY | O_CREAT)) == -1)
			{
				fprintf(stderr, "Can't create new database files");
				exit(1);
			}
			else
			{
				if((*guests = open("guests.db", O_WRONLY | O_CREAT)) == -1)
				{
					fprintf(stderr, "Can't create new database files");
					exit(1);
				}
				
				
			}
			
		}
	}
	else 
	{
		
	}
}
int
liberar(char * huesped, char * numero)
{
	printf("LIBERAR huesped: %s numero: %s\n", huesped, numero);
	return 1;
}

int
ocupar(char * huesped, char * numero)
{
	printf("OCUPAR huesped: %s numero: %s\n", huesped, numero);
		return 1;
}

int
reservar(char * huesped)
{
	printf("RESERVAR huesped: %s\n", huesped);
		return 1;
}

int
listar(char * huesped)
{
	printf("LISTAR huesped: %s \n", huesped);
		return 1;
}


/* Extra functions */
static void 
siginthandler(int sig)
{
	printf("\nExit!\n");
	exit(1);
}


